
import 'dart:async';
import 'dart:convert';
import 'package:flutter/services.dart';

class FlutterCardPlugin {

  static const MethodChannel _channel = MethodChannel('flutter_card_plugin');

  static final FlutterCardPlugin instance = FlutterCardPlugin._internal();

  Function(CardValue cardValue)? slotCardCallBack;
  Function()? slotCardFail;

  ///工厂构造函数
  factory FlutterCardPlugin() {
    return instance;
  }

  ///构造函数私有化，防止被误创建
  FlutterCardPlugin._internal() {
    _channel.setMethodCallHandler((MethodCall call) async {
      switch (call.method) {
        case "slotCardCallBack":
          if (call.arguments != null) {
            print("刷卡成功");
            CardValue device = CardValue.fromJson(jsonDecode(call.arguments));
            slotCardCallBack?.call(device);
          } else {
            //连接失败或者断开连接
            print("刷卡失败");
            slotCardFail?.call();
          }
          break;
      }
    });
  }

  ///获取设备序列号
  Future<String> serialNumber() async {
    return await _channel.invokeMethod("serialNumber");
  }

  ///设置状态栏
  Future<String> showOrHideStatusBar({required Map<String, dynamic> data}) async {
    return await _channel.invokeMethod("showOrHideStatusBar", data);
  }


  ///电子班牌重启
  Future<String> restart() async {
    return await _channel.invokeMethod("restart");
  }


  ///电子班牌关机
  Future<String> powerOff() async {
    return await _channel.invokeMethod("powerOff");
  }

  ///电子班牌静默安装应用
  Future<String> installAPK({required Map<String, dynamic> data}) async {
    return await _channel.invokeMethod("installAPK",data);
  }


  ///页面关闭销毁资源
  Future<String?> destroy() async {
    return await _channel.invokeMethod("destroy");
  }

}

class CardValue {
  String? name;

  CardValue({this.name});

  CardValue.fromJson(Map<String, dynamic> json) {
    name = json['name'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['name'] = name;
    return data;
  }
}
